package com.ruoyi.common.utils;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.ruoyi.common.exception.ServiceException;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Map;

/**
 * 百度、腾讯、高德地图路线规划
 *
 * @Author: triones
 */
public class MapRoutePlan {

    /**
     * 高德web服务key
     */
    public static final String GAOEKEY = "28191a9e502737455d6769caede2bb8e";

    /**
     * 高德地图路线规划
     * @param origin 起点
     * @param destination 终点
     * @return 两点路线距离
     */
    public static double gaoDeStance(String origin,String destination) {
        /**
         * String origin = "116.45925,39.910031" 起点经纬度，格式为：纬度,经度；小数点后不超过6位
         * String destination = "116.587922,40.081577" 终点经纬度，格式为：纬度,经度；小数点后不超过6位
         */
        String httpUrl = "https://restapi.amap.com/v5/direction/driving?origin="
            + origin + "&destination="
            + destination + "&key="
            + GAOEKEY + "&strategy=2&output=JSON";
        double distance = 0;
        StringBuilder json = new StringBuilder();
        try {
            URL url = new URL(httpUrl);
            URLConnection urlConnection = url.openConnection();
            BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), "UTF-8"));
            String inputLine = null;
            while ((inputLine = in.readLine()) != null) {
                json.append(inputLine);
            }
            in.close();
        } catch (MalformedURLException e) {
            throw new ServiceException("距离计算异常");
        } catch (IOException e) {
            throw new ServiceException("距离计算异常");
        }
        String data = json.toString();
        if (data != null && !"".equals(data)) {
            Map map = JSONUtil.toBean(data, Map.class);
            if ("1".equals(map.getOrDefault("status", "1").toString())) {
                Map childMap = (Map) map.get("route");
                JSONArray jsonArray = (JSONArray) childMap.get("paths");
                JSONObject jsonObject = jsonArray.getJSONObject(0);
                distance = Double.parseDouble(jsonObject.getStr("distance"));
            }
        }
        return distance / 1000;
    }

    public static void main(String[] args) {
//        double v = gaoDeStance("116.4592500,39.9100310", "116.5879220,40.0815770");
//        System.out.println("v = " + v);
        System.out.println("args = " + 0 / 1000);
    }
}
